import { createRouter, createWebHashHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Main from "../views/Main.vue";
import Cookie from 'js-cookie'
import Home from "@/views/Home.vue";
import User from "@/views/User.vue";
import Mall from "@/views/Mall.vue";
import PageOne from "@/views/PageOne.vue";
import PageTwo from "@/views/PageTwo.vue";
import Menu from "@/views/Menu.vue";
import Role from "@/views/Role.vue";

const routes = [
    // 主路由
    {
        path: '/',
        name:'Main',
        component: Main,
        redirect: '/home', // 重定向
        children: [
            // 子路由
            { path: '/home', name: 'home', component: Home }, // 首页
            { path: '/user', name: 'user', component: User }, // 用户管理
            { path: '/mall', name: 'mall', component: Mall }, // 商品管理
            { path: '/page1', name: 'page1', component: PageOne }, // 测试测试1
            { path: '/page2', name: 'page2', component: PageTwo }, // 测试测试2
            { path: '/menu', name: 'menu', component: Menu }, // 测试测试2
            { path: '/role', name: 'role', component: Role }, // 测试测试2
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    }
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

router.beforeEach((to, from, next) => {
    const token = Cookie.get('token')
    console.log("12312313131")

    if (!token && to.name !== 'login') {
        next({ name: 'login' })
    } else if (token && to.name === 'login') {
        next({ name: 'home' })
    } else {
        next()
    }
});
console.log('Routes:', routes);
export default router;